package actions;
/**
 * @author Bailey Steinfadt
 * 
 * This class highlights the opening and closing braces 
 * when the cursor is next to the closing brace
 */
import java.awt.Color;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;


public class ParenHighlight extends AbstractAction{

	private static final long serialVersionUID = 1L;

	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		// Get the text pane and text
		JTextPane pane = (JTextPane)arg0.getSource();
		String text = pane.getText();
		//set variables for searching through the text for braces
		int sem = 0;
		int position = pane.getCaretPosition();
		int open = 0, close = position;
		
		StyledDocument doc = pane.getStyledDocument();
	    Style styleGreen = pane.addStyle("Green", null);
	    StyleConstants.setForeground(styleGreen, Color.green);
		
	    //just looking for the closing brace to THIS brace in this one
		do{
			
			//if there's a closing brace, add one to the semaphore
			if(text.charAt(position) == '}') {
				sem++;
			}
			//if there's an opening brace, subtract one from the semaphore
			if(text.charAt(position) == '{') {
				open = position;
				sem--;
			}
			
			//move back one position
			position--;

		}while(sem > 0);
	    
		//temporarily highlight the braces green to denote that it's been closed
		//or that it is the opening brace for the one next to the cursor
		doc.setCharacterAttributes(open, 0, pane.getStyle("Green"), true);
		doc.setCharacterAttributes(close, 0, pane.getStyle("Green"), true);

	//these will need to be turned off as soon as the cursor moves away from the closing brace
	}

	

}
